<?php

namespace app\model;

use app\utils\Md5Service;
use \think\facade\Db;
use think\facade\Log;

class PartnerRoleModel
{

    public static function getAllRole($param)
    {
        return Db::table('xl_partner_role')->where('status', '<', 3)->where('partner_id', '=', $param['partner_id'])->select();
    }

    /**
     * 获取所有的权限菜单列表
     * @return void
     */
    public static function GetAllPermission()
    {
        return Db::table('xl_partner_permission')->where('status', '=', 1)
            ->select();
    }

    /**
     * 根据手机号密码获取登录信息是否正确
     * @return void
     */
    public static function GetPartneInfo($param)
    {
        return Db::table('xl_partner_user')->where('mobile', $param['mobile'])
            ->where('password', Md5Service::encryptMd5($param['password'], $param['salt']))
            ->find();
    }

    public static function UpdatePartnerLoginInfo($data, $param)
    {
        $update['login_ip'] = $param['login_ip'];
        $update['login_num'] = $data['login_num'] + 1;
        $update['login_time'] = getNowDateTime();
        Db::startTrans();
        try {
            Db::table('xl_partner_user')->where(['id' => $data['id']])->update($update);
            // 提交事务
            Db::commit();
            return true;
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return false;
        }
    }

    public static function getRoleByUid($uid = 0)
    {
        return Db::table('xl_partner_user')->where(['id' => $uid])->field('id,role_id')->find();
    }

    public static function getPartnerIdByUid($uid = 0)
    {
        return Db::table('xl_partner_user')->where(['id' => $uid])->field('id,role_id,partner_id')->find();
    }

    //根据partner_id获取所有的user
    public static function getPartnerUserByPartnerId($param)
    {
        return Db::table('xl_partner_user')->alias('user')
            ->join('xl_partner_role role', 'user.role_id = role.id', 'left')
            ->where(['user.partner_id' => $param['partner_id']])
            ->field('user.id,user.name,user.mobile,user.status,user.login_time,user.nickname,role.name as role_name')
            ->select()->toArray();
    }

    //添加合作商新角色

    public static function add_role($data)
    {
        return Db::table('xl_partner_role')->insertGetId($data);
    }

    //修改合作商新角色

    public static function modify_role($data, $role_id)
    {
        return Db::table('xl_partner_role')->where('id', '=', $role_id)->update($data);
    }

    //根据手机号查询合作商用户角色

    public static function find_role($where)
    {
        return Db::table('xl_partner_role')->where($where)->find();
    }

    //根据手机号查询合作商用户角色

    public static function del_role($where)
    {
        return Db::table('xl_partner_role')->where($where)->delete();
    }


}
